package main

func main() {

}

type ListNode struct {
	Val  int
	Next *ListNode
}

//https://leetcode-cn.com/problems/linked-list-cycle-ii/
func detectCycle(head *ListNode) *ListNode {
	//快慢指针用来找环
	fast, low := head, head
	for fast != nil && fast.Next != nil {
		fast = fast.Next.Next
		low = low.Next
		if fast == low {
			break
		}
	}
	//不相等 则没环
	if fast != low {
		return nil
	}
	result := head
	//若只有一个节点说明无环
	if result == nil || result.Next == nil {
		return nil
	}
	//环与头结点一块走，找环的位置
	for fast != nil && fast != result {
		fast = fast.Next
		result = result.Next
	}
	return result
}
